﻿/*
File: SectionBasedBinary.cs
Project: Themaopdracht 7
Author: Roel Blaauwgeers

Description:
Sections a bitmap, calculates a threshold and creates a binary image for every section.
+++++++++++++++++
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace THO7_Team8.Filters
{
    class SectionBasedBinary : VisionAlgorithm
    {
        public SectionBasedBinary(String name) : base(name) { }
        public override System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage)
        {
            Bitmap bmp = new Bitmap(sourceImage);
            BitmapData bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            unsafe
            {
                byte* p = (byte*)bmd.Scan0;
                int Bpp = bmd.Stride / bmd.Width;
                int totalBytes = bmd.Stride * bmd.Height;

                int grayscaleValue;
                int filterSize = 100 * Bpp;
                Console.Write("bmpstr: " + filterSize);

                //               for (int i = 0; i < totalBytes; i += Bpp)
                //             {

                for (int i = ((bmd.Width) + Bpp) * (filterSize / 2); i < totalBytes - (bmd.Width + Bpp) * (filterSize / 2); i += Bpp)
                {

                    for (int y = (-(filterSize / 2)); y <= (filterSize / 2); y += Bpp)
                    {
                        for (int x = (-(filterSize / 2)); x <= (filterSize / 2); x += Bpp)
                        {
                            //create binary
                            grayscaleValue = (int)Math.Round((p[i] * 0.11 + p[i + 1] * 0.59 + p[i + 2] * 0.3));
                            if (grayscaleValue > 128)
                            {
                                p[i] = p[i + 1] = p[i + 2] = 255;
                            }
                            else
                            {
                                p[i] = p[i + 1] = p[i + 2] = 0;
                            }
                        }
                    }
                    i = totalBytes;



                }
            }
            bmp.UnlockBits(bmd);
            return bmp;

        }
    }
}
